﻿module Sustainalytics.Portfolio {
    import Common = Sustainalytics.Common;
    import SearchPortfolio = Sustainalytics.Portfolio.PortfolioSearchController;

    // Portfolio List controller
    export class PortfolioAddController {

        public portfolio: PortfolioDto;
        public portfolioAddUpdate: PortfolioAddDto;
        public portfolioFilter: PortfolioFilterDto;
        public isShared: boolean;
        public portfolioSearch: string;
        private accountId: string;
        private userId: string;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private PortfolioService: PortfolioService,
            private PortfolioCompanyService: PortfolioCompanyService,
            private notificationFactory: Common.INotificationFactory,
            private $modal: Common.IModal,
            private $modalInstance: Common.IModalInstance,
            private filterId: string
            ) {

            var ctx = this;
            ctx.isShared = false;
            ctx.portfolioAddUpdate = new PortfolioAddDto();
            ctx.portfolioFilter = new PortfolioFilterDto();
            ctx.portfolioSearch = '';

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            $scope['portfolioAdd'] = ctx;
        }

        cancel() {
            this.$modalInstance.dismiss('cancel');
        }

        public selectPortfolioAdd(item) {
            var ctx = this;
            ctx.portfolioAddUpdate.portfolioName = item.name;
            ctx.portfolioAddUpdate.portfolioId = item.id;
            ctx.portfolioFilter.namePortfolio = item.name;
            ctx.portfolioFilter.portfolioId = item.id;
            ctx.portfolioFilter.sharingStatus = ctx.isShared ? PortfolioSharingStatus.Shared : PortfolioSharingStatus.Private;
            ctx.portfolioFilter.portfolioType = PortfolioTypes.Custom;

            //ctx.$rootScope['screeningExportDetails'].SelectedPortfolio = item.name;
        }

        public addPortfolio(): ng.IPromise<{}> {
            var ctx = this;

            var portfolioCountTemp : number;

            ctx.portfolioAddUpdate.filterId = ctx.filterId;
            ctx.portfolioAddUpdate.isValid = true;

            ctx.portfolioFilter.isMyPortfolio = true;
            ctx.portfolioFilter.namePortfolio = ctx.portfolioSearch;
            ctx.portfolioFilter.isNameEqual = true;



            ctx.portfolioAddUpdate.portfolioName = ctx.portfolioSearch;
            ctx.portfolioAddUpdate.sharingStatus = ctx.isShared ? PortfolioSharingStatus.Shared : PortfolioSharingStatus.Private;

            var tempFilter: PortfolioFilterDto = new PortfolioFilterDto();
            tempFilter.portfolioType = PortfolioTypes.All;
            tempFilter.namePortfolio = this.portfolioSearch;
            tempFilter.sharingStatus = PortfolioSharingStatus.All;
            tempFilter.isNameEqual = true;


            //get portfolios count
            var promiseCount: ng.IPromise<PortfolioListDto> = ctx.PortfolioService.getPortfolioCount(tempFilter, ctx.accountId, ctx.userId);

            //on success 
            promiseCount.then(count => {

                portfolioCountTemp = count.count;
                var portfolioTemp = count.portfolios[0];
                if (portfolioCountTemp === 0) {
                    this.$rootScope['loading'] = true;
                    var promiseAddPortfolio: ng.IPromise<{}> = this.PortfolioService.addPortfolios(this.portfolioAddUpdate);

                    //on success 
                    promiseAddPortfolio.then(() => {
                        this.$rootScope['loading'] = false;
                        this.cancel();
                    });
                }
                else if (portfolioCountTemp >= 1) {
                    if (!portfolioTemp.isSystemPortfolio) {
                        var modalInstancePortfolio = this.$modal.open({
                            templateUrl: 'Views/Portfolio/portfolioExists_dialog.tpl.html',
                            controller: 'PortfolioCheckController',
                            size: 'lg',
                            backdrop: 'static',
                            resolve: {
                                message() {
                                    return "Are you sure you want to overwrite the existing Portfolio?";
                                },
                                informationMessage() {
                                }
                            }
                        });

                        modalInstancePortfolio.result.then((out) => {
                            if (out['portfolioCheck'] === true) {
                                this.$rootScope['loading'] = true;
                                var promiseUpdatePortfolio: ng.IPromise<{}> = this.PortfolioService.updatePortfolios(this.portfolioAddUpdate);

                                this.cancel();
                            }
                            else {
                                $("#portfolioAddSearchInput").focus();
                            }

                        }).finally(() => {
                            this.$rootScope['loading'] = false;
                        });
                    }
                    else
                    {
                        this.notificationFactory.error("","A portfolio with this name already exists!");
                        $("#portfolioAddSearchInput").focus();
                    }
                }
            });
            return promiseCount;
        }

        setPrivate() {
            var ctx = this;
            ctx.isShared = false;
        }

        setShared() {
            var ctx = this;
            ctx.isShared = true;
        }
    }


    // register controller with News Angular module
    angular.module(portfolioModuleName).controller('PortfolioAddController',
        ['$rootScope', '$scope', '$q', '$location', 'PortfolioService', 'PortfolioCompanyService', 'notificationFactory', '$modal',
            '$modalInstance', 'filterId', PortfolioAddController]);
} 
